package com.csi.controller.user;

import com.csi.domain.UserBook;
import com.csi.service.UserBookService;
import com.csi.utils.JsonResult;
import com.csi.utils.JwtUtil;
import com.csi.utils.ReturnResults;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/userBook")
public class UserBookController {

    @Autowired
    private UserBookService userBookService;

    /**
     * 保存预定信息
     */
    @Operation(summary = "保存预定信息", description = "用户根据提供的信息进行房间预定")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "2001", description = "预定成功", content = @Content(schema = @Schema(implementation = JsonResult.class))),
            @ApiResponse(responseCode = "4001", description = "预定失败", content = @Content)
    })
   @PostMapping("saveBook")
   public Object saveBook(
           HttpServletRequest request,
   @Parameter(description = "入住时间（格式：yyyy-MM-dd HH:mm:ss）", required = true, example = "2024-12-15 10:33:00")
   @RequestParam(value = "check_time") String checkTime,
   @Parameter(description = "离开时间（格式：yyyy-MM-dd HH:mm:ss）", required = true, example = "2024-12-20 10:33:00")
   @RequestParam("leave_time") String leaveTime,
   @Parameter(description = "房间数量", required = true, example = "1")
   @RequestParam("room_num") int roomNum,
   @Parameter(description = "预定价格", required = true, example = "699.00")
   @RequestParam("book_price") double bookPrice,
   @Parameter(description = "联系电话", required = true, example = "13800001234")
   @RequestParam("phone") String phone,
   @Parameter(description = "酒店ID", required = true, example = "2")
   @RequestParam("hotelId") long hotelId,
   @Parameter(description = "房型ID", required = true, example = "3")
   @RequestParam("roomtypeId") long roomTypeId) {
        System.out.println("request = " + request +"checkTime = " + checkTime + "leaveTime = " + leaveTime + "roomNum = " + roomNum);

        // 获取当前用户的ID

//        if (token == null || token.isEmpty()) {
//            return new JsonResult(ReturnResults.ACCESS_FAILED, "无效的Token");
//        }
        String token = JwtUtil.getToken("zhangsan", 1);
//        String token = request.getHeader("token");
        long userId = JwtUtil.getTokenBody(token).get("userId", Long.class);

        // 调用服务层保存预定信息
        int result = userBookService.saveBook(userId, checkTime, leaveTime, roomNum, bookPrice, phone, hotelId, roomTypeId);

        // 返回结果
        if (result > 0) {
            return new JsonResult(ReturnResults.ACCESS_SUCCESS, result, "预定成功！");
        } else {
            return new JsonResult(ReturnResults.ACCESS_FAILED, "预定失败！");
        }
    }

    /**
     * 处理支付请求
     */
    @Operation(summary = "处理支付请求", description = "用户根据提供的预定信息完成支付")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "2001", description = "支付成功", content = @Content(schema = @Schema(implementation = JsonResult.class))),
            @ApiResponse(responseCode = "4001", description = "支付失败", content = @Content),
            @ApiResponse(responseCode = "4001", description = "无效的Token", content = @Content)
    })
    @PostMapping(value = "payment", produces = "application/json;charset=utf-8")
    public Object payment(
            HttpServletRequest request,
            @Parameter(description = "预定信息", required = true)
            @RequestBody UserBook userBook) {

        // 获取当前用户的ID
//        String token = request.getHeader("token");
//        if (token == null || token.isEmpty()) {
//            return new JsonResult(ReturnResults.ACCESS_FAILED, "无效的Token");
//        }
        String token = JwtUtil.getToken("zhangsan", 1);

        long userId = JwtUtil.getTokenBody(token).get("userId", Long.class);
        // 设置用户ID到UserBook对象中

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Timestamp check = null;
        Date date1 = null;
        try {
            Date date = sdf.parse(String.valueOf(userBook.getCheckTime()));
            check = new Timestamp(date.getTime());

            date1 = sdf.parse(String.valueOf(userBook.getLeaveTime()));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        Timestamp leave = new Timestamp(date1.getTime());

        userBook.setCheckTime(check);
        userBook.setLeaveTime(leave);
        userBook.setUserId(userId);
        // 调用服务层处理支付
        int result = userBookService.payment(userBook);

        // 返回结果
        if (result > 0) {
            return new JsonResult(ReturnResults.ACCESS_SUCCESS, result, "支付成功！");
        } else {
            return new JsonResult(ReturnResults.ACCESS_FAILED, "支付失败！");
        }
    }

    /**
     * 状态修改的逻辑
     * 当用户支付成功之后就将状态改为带入住
     * 当用户到店办理入住时,会将状态改为入住中
     * 当用户离店时间到时或办理离店时改为待评价
     * 评价完成之后改为已完成
     * @param userBook
     * @return
     * @throws ParseException
     */
    /**
     * 标记订单完成
     */
    @Operation(summary = "标记订单完成", description = "根据提供的订单ID更新订单状态为已完成")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "2001", description = "操作成功", content = @Content(schema = @Schema(implementation = JsonResult.class))),
            @ApiResponse(responseCode = "4001", description = "操作失败", content = @Content),
            @ApiResponse(responseCode = "4001", description = "订单ID不存在", content = @Content)
    })
    @PostMapping("/completed")
    public Object completed(
            @Parameter(description = "预定信息", required = true)
            @RequestBody UserBook userBook) {

        long bookId = userBook.getId();

        // 调用服务层标记订单为已完成
        System.out.println("12312312313======================");
        int result = userBookService.completed(bookId);
        System.out.println("支付了======================");
        // 返回结果
        if (result > 0) {
            return new JsonResult(ReturnResults.ACCESS_SUCCESS, result, "订单已成功标记为已完成！");
        } else {
            return new JsonResult(ReturnResults.ACCESS_FAILED, "订单状态更新失败，请检查订单ID是否正确！");
        }
    }

    /**
     * 标记订单已评价
     */
    @Operation(summary = "标记订单已评价", description = "根据提供的订单ID更新订单状态为已评价")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "2001", description = "操作成功", content = @Content(schema = @Schema(implementation = JsonResult.class))),
            @ApiResponse(responseCode = "4001", description = "操作失败", content = @Content),
            @ApiResponse(responseCode = "4001", description = "订单ID不存在或无效", content = @Content)
    })
    @PostMapping("/evaluated")
    public Object evaluated(
            @Parameter(description = "预定信息", required = true)
            @RequestBody UserBook userBook) {

        long bookId = userBook.getId();
        if (bookId <= 0) {
            return new JsonResult(ReturnResults.ACCESS_FAILED, "无效的订单ID");
        }

        // 调用服务层标记订单为已评价
        int result = userBookService.evaluated(bookId);

        // 返回结果
        if (result > 0) {
            return new JsonResult(ReturnResults.ACCESS_SUCCESS, result, "评价成功！");
        } else {
            return new JsonResult(ReturnResults.ACCESS_FAILED, "评价失败，请检查订单ID是否正确或订单状态是否允许评价！");
        }
    }


    @RequestMapping("secKill")
    public Object secKill(HttpServletRequest request,
                          @Parameter(description = "入住时间（格式：yyyy-MM-dd HH:mm:ss）", required = true, example = "2024-12-15 10:33:00")
                          @RequestParam("check_time") String checkTime,
                          @Parameter(description = "离开时间（格式：yyyy-MM-dd HH:mm:ss）", required = true, example = "2024-12-20 10:33:00")
                          @RequestParam("leave_time") String leaveTime,
                          @Parameter(description = "房间数量", required = true, example = "1")
                          @RequestParam("room_num") int roomNum,
                          @Parameter(description = "预定价格", required = true, example = "699.00")
                          @RequestParam("book_price") double bookPrice,
                          @Parameter(description = "联系电话", required = true, example = "13800001234")
                          @RequestParam("phone") String phone,
                          @Parameter(description = "酒店ID", required = true, example = "2")
                          @RequestParam("hotelId") long hotelId,
                          @Parameter(description = "房型ID", required = true, example = "3")
                          @RequestParam("roomtypeId") long roomTypeId) {

        //处理业务秒杀
        System.out.println("request = " + request + ", checkTime = " + checkTime + ", leaveTime = " + leaveTime + ", roomNum = " + roomNum + ", bookPrice = " + bookPrice + ", phone = " + phone + ", hotelId = " + hotelId + ", roomTypeId = " + roomTypeId);
//        String token = request.getHeader("token");
        String token = JwtUtil.getToken("zhangsan", 1);

        long userId = JwtUtil.getTokenBody(token).get("userId", Long.class);
        return userBookService.sec(userId, checkTime, leaveTime, roomNum, bookPrice, phone, hotelId, roomTypeId);

    }


}
